const medica = require('../../utils/medica.common.js')
import api from '../../../api/index'
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		bindDeviceId: null,
		devicelist: [],
		showDevice: false,
		actions: [],
		bindDevice: [],
		saveDevice: {},
		showDialog: false,
		bindDeviceTextInfo: '',
		loading: false,
		currentDevice: null,
		timer: null,
		bleAvaible: true,
		saveDataList: [],
		beforeClose: null,
		timeValue: null
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		this.get()
		// this.openBluetoothAdapter()
		// this.onBluetoothAdapterStateChange()
	},
	// 初始化蓝牙
	openBluetoothAdapter() {
		wx.openBluetoothAdapter({
			success: (res) => {
				this.setData({
					bleAvaible: true
				})
				console.log(res, '蓝牙初始化成功')
			},
			fail: (error) => {
				console.log(error, '蓝牙初始化失败')
				this.setData({
					bleAvaible: false
				})
			},
		})
	},
	// 监听蓝牙开关状态
	onBluetoothAdapterStateChange() {
		medica.b501tBleApi.onBluetoothAdapterStateChange((available) => {
			// available: true 蓝牙打开, false 蓝牙关闭
			this.setData({
				bleAvaible: available
			})
		});
	},
	// 获取蓝牙适配器状态
	doGetBluetoothAdapterState() {
		bleUtils.getBluetoothAdapterState()
	},
	onCancel() {
		this.dialogClost()
		clearInterval(this.timeValue)
		this.setData({
			bindDeviceTextInfo: ''
		})
	},
	createDiaTitle() {
		let num = 15
		let value = ''
		this.timeValue = setInterval(() => {
			value = `蓝牙搜索中(${num}s)...`
			if (num === 0) {
				clearInterval(this.timeValue)
				value = `蓝牙搜索完成`
			} else {
				num --
			}
			this.setData({
				bindDeviceTextInfo: value
			})
		}, 1000)
	},
	onConfirm() {
    this.dialogClost()
		clearInterval(this.timeValue)
    // bleUtils.stopSearchBlueTooth()
		this.createDiaTitle()
    this.onScan()
  },
	// 封装异步关闭函数
  dialogClost() {
    this.setData({
      beforeClose: (action) =>
        new Promise((resolve) => {
          if (action === 'confirm') {
            // 确定按钮
            resolve(false)
          } else if (action === 'cancel') {
            // 取消按钮
            resolve(true)
          }
        }),
    })
  },
	// 链接设备
	goBindEq() {
		if (!this.data.bleAvaible) {
			wx.showToast({
				title: '蓝牙初始化失败',
				icon: 'none',
				duration: 2000
			})
			return
		}
		this.setData({
			showDialog: true
		})
		this.onConfirm()
		// this.createTimeInter()
	},
	onSelectA(e) {
    const value = e.currentTarget.dataset.item
		this.setData({
			saveDevice: value
		})
		const device = this.data.bindDevice.find(item => {
			return item.name === this.data.saveDevice.name
		})
		let saveDataList = []
		// 如果绑定的有该设备
		if(device) {
			wx.showToast({
				title: '该设备已绑定',
				icon: 'none',
				duration: 3000
		  })
		} else {
			const bindDevice = { name: this.data.saveDevice.name, deviceId: this.data.saveDevice.deviceId, mac: this.data.saveDevice.mac }
			saveDataList = this.data.bindDevice.concat(bindDevice)
			this.setData({
				saveDataList: saveDataList
			})
			this.onBind()
		}
  },
	onScan() {
		medica.b501tBleApi.scanBleDevices(15000, false, (device) => {
			console.log(device, 'devicedevicedevice')
			if (device.name === '0994' || device.localName === '0994') {
				console.log('找到了设备', device)
				this.setData({
					currentDevice: device
				})
				const actions = [
					{ name: device.name, subname: device.deviceId, deviceId: device.deviceId, mac: device.mac },
				]
				this.setData({
					showDialog: false,
					actions: actions
				})
				// 搜索到可用的蓝牙设备，停止搜索
				this.setData({ showDevice: true });
				return
			}
		})
	},
	// 删除设备
	delEq(e) {
		const name = e.currentTarget.dataset.name
		const data = this.data.bindDevice.filter(item => {
			return item.name !== name
		})
		const deldata = this.data.bindDevice.filter(item => {
			return item.name === name
		})
		// this.doDeleteMonitorDevice(deldata[0])
		this.putData(data, '删除')
	},
	onClose() {
		this.setData({ showDevice: false });
	},
	onSelect(event) {
		console.log(event.detail, 'event.detail')
		this.setData({
			saveDevice: event.detail
		})
		const device = this.data.bindDevice.find(item => {
			return item.name === this.data.saveDevice.name
		})
		let saveDataList = []
		// 如果绑定的有该设备
		if (device) {
			wx.showToast({
				title: '该设备已绑定',
				icon: 'none',
				duration: 3000
			})
		} else {
			const bindDevice = { name: this.data.saveDevice.name, deviceId: this.data.saveDevice.deviceId, mac: this.data.saveDevice.mac }
			saveDataList = this.data.bindDevice.concat(bindDevice)
			this.setData({
				saveDataList: saveDataList
			})
			this.onBind()
		}
	},
	// 绑定设备
	onBind() {
		console.warn(this.data.saveDevice, '--------------开始绑定设备')
		this.setData({
			bindDeviceTextInfo: '正在绑定设备'
		})
		this.setData({
			showDialog: true
		})
		medica.b501tBleApi.connectDevice(this.data.saveDevice.deviceId, 20000, (ret, retDeviceId) => {
			console.log(ret, retDeviceId, '绑定结束')
			if (ret) {
				this.putData(this.data.saveDataList, '保存')
				this.setData({
					bindDeviceTextInfo: '设备绑定成功'
				})
				setTimeout(() => {
					this.setData({
						showDialog: false,
					})
				}, 500);
				let pages = getCurrentPages();  //获取当前页面
				let beforePage = pages[pages.length - 2]  //获取上一个页面的实例
					// beforePage.setUserId()
					// beforePage.setMonitorTime()
					// beforePage.getMonitorTime()
				if (beforePage.getHistoryDataSummary) {
					beforePage.getUserId()
					console.log('nengjinlaima---------');
					beforePage.getMonitorTime()
					setTimeout(() => {
						beforePage.getHistoryDataSummary()
					}, 3000)
				}
			} else {
				this.setData({
					bindDeviceTextInfo: '设备绑定失败'
				})
				setTimeout(() => {
					this.setData({
						showDialog: false,
					})
				}, 500);
			}
		})
	},
	putData(deviceIdList, type) {
		let num = [{ name: 'sleep', devicelist: deviceIdList }]
		num = JSON.stringify(num)
		this.doSavedevice(num, type)
	},
	// 储存设备
	async doSavedevice(result, type) {
		try {
			await api.post('/api/user/storage/set', {
				data: {
					'key': 'devicelist',
					'value': result
				}
			})
			wx.showToast({
				title: `${type}成功`,
				icon: 'none',
				duration: 3000
			})
			this.setData({ showDevice: false });
			this.get()
		} catch (e) {
			console.log('put->', e)
		}
	},
	async get() {
		this.setData({
			bindDevice: []
		})
		try {
			this.setData({
				loading: true
			})
			const res = await api.post('/api/user/storage/get', {
				data: {
					'key': 'devicelist'
				}
			})
			if (res[0].value) {
				var array = JSON.parse(res[0].value)
				const listValue = array.filter(item => item.name === 'sleep')
				if (listValue.length > 0) {
					this.setData({
						bindDevice: listValue[0].devicelist
					})
				}
			}
			this.setData({
				loading: false
			})
		} catch (e) {
			console.log('get->', e)
			return null
		}
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})